package com.xzj.admin.resource.analysis.handle.init;

import cn.hutool.core.util.StrUtil;
import com.xzj.admin.analysis.base.manage.MessageAnalysisFactory;
import com.xzj.admin.resource.analysis.cache.BaseCache;
import com.xzj.admin.resource.analysis.cache.GroovyScriptCache;
import com.xzj.admin.resource.analysis.domain.entity.ResMessageSource;
import com.xzj.admin.resource.analysis.domain.props.BaseProps;
import com.xzj.admin.resource.analysis.domain.props.CloudProps;
import com.xzj.admin.resource.analysis.mapper.BaseMapper;
import jakarta.annotation.Resource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: xzj-admin
 * @ClassName: AppInitHandle
 * @description: 解析处理初始化操作
 * @author: XiaZunJun
 * @create: 2024-11-04 15:31
 */
@Component
public class AppInitHandle implements ApplicationRunner {

    @Resource
    private BaseMapper baseMapper;

    @Resource
    private BaseProps baseProps;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        CloudProps cloudProps = baseProps.getCloud();
        // 获取需要处理的消息源
        List<ResMessageSource> resMessageSources = baseMapper.queryCloudSource(cloudProps);
        for(ResMessageSource messageSource:resMessageSources){
            BaseCache.putMessageSource(messageSource);
            // 判断是否存在ID脚本
            if(StrUtil.isEmpty(messageSource.getKeyScriptId())
                    || StrUtil.isEmpty(messageSource.getIdScriptContent())){
                throw new RuntimeException("同步资源失败,请检查消息源 {"+messageSource.getSourceName()+"} ID脚本是否存在");
            }
            // 加载groovy脚本
            GroovyScriptCache.putScript(messageSource.getKeyScriptId(),messageSource.getIdScriptContent());
            // 判断是否存在推送前置脚本
            if(StrUtil.isNotEmpty(messageSource.getPushPreScript())
                    && StrUtil.isNotEmpty(messageSource.getPushScriptContent())){
                GroovyScriptCache.putScript(messageSource.getPushPreScript(),messageSource.getPushScriptContent());
            }
            // 判断是否存在入库前置脚本
            if(StrUtil.isNotEmpty(messageSource.getDatabasePreScript())
                    && StrUtil.isNotEmpty(messageSource.getDatabaseScriptContent())){
                GroovyScriptCache.putScript(messageSource.getDatabasePreScript(),messageSource.getDatabaseScriptContent());
            }
        }
        // 修改状态初始化完成
        BaseCache.putInitFinish();
    }
}
